<?php

	session_start();

	require('setlang.php');
	require('Models/basics.php');
	require('Models/connectBDD.php');
	require('Models/formerrors.php');
	require('Models/editProfile.php');
	require('Models/adresse.php');
	require('Models/ariane.php');
	
	$Ariane = getArianeGenealogy();
	
	$connexion = PDO_BDD_connect();
	
	if (!isValidSessionUser($connexion) || !areValidUserRights($connexion))
	{
		header('Location:logout.php');
	}
	//Si on change le mail, on fait les tests adéquats et l'update
	if (isset($_POST["validermail"]))
	{
		$errors = getFormErrors(array("e-mail","mail"),"POST");
		
		if (empty($errors) && !alreadyExistsMail($connexion,$_POST["mail"]))
		{
			$successMail = updateMail($connexion,$_POST["mail"]);
		}
		
	}
	//De même pour le mot de passe
	else if (isset($_POST["validerpass"]))
	{
		$errors = getFormErrors(array("e-mail","mdp","verifmdp","oldmdp"),"POST");
		
		if (empty($errors))
		{
			if (sha1($_POST['oldmdp']) == $_SESSION['passhash'])
			{
				if ($_POST['mdp'] == $_POST['verifmdp'])
				{
					$successPass = updatePassword($connexion,$_POST['mdp']);
				}
				else
				{
					$newPassNotEquals = true;
				}				
			}
			else
			{
				$oldPassNotGood = true;
			}
		}
	}
	//Pour le téléphone
	else if (isset($_POST["validerphone"]))
	{
		$errors = getFormErrors(array("e-mail","telephone","mobile"),"POST");
		
		if (array_search("telephone",$errors) !== false && array_search("mobile",$errors) === false)
		{
			unset($errors[array_search("telephone",$errors)]);
		}
		else if (array_search("mobile",$errors) !== false && array_search("telephone",$errors) === false)
		{
			unset($errors[array_search("mobile",$errors)]);
		}
		
		if (empty($errors))
		{
			$successPhone = updatePhones($connexion,$_POST['telephone'],$_POST['mobile']);
		}
		
	}
	//Pour la langue
	else if (isset($_POST["validerlangue"]))
	{
		$errors = getFormErrors(array("e-mail","langue"),"POST");
		
		if (empty($errors))
		{
			$successLanguage = updateLanguage($connexion,$_POST['langue']);
		}
		
	}
	//Pour l'adresse
	else if (isset($_POST["valideradresse"]))
	{
		
		$errors = getFormErrors(array("e-mail","numero","rue_1","rue_2","rue_3","cp","ville","pays"),"POST");
		
		if (isset($_POST["rue_1"]))
		{
			if (array_search("rue_2",$errors) !== false)
			{
				unset($errors[array_search("rue_2",$errors)]);
			}
			if (array_search("rue_3",$errors) !== false)
			{
				unset($errors[array_search("rue_3",$errors)]);
			}
		}
		
		if (empty($errors))
		{
			
			$adresse = existsAddress($connexion);
			
			if ($adresse == 0) {
			
				$adresse = addAddress($connexion);
				
				if ($adresse == -1) {
					die("Une erreur s'est produite lors de l'ajout de l'adresse. Veuillez contactez l'administrateur.");
				}
			
			}
			
			$successAddress = updateAddress($connexion,$adresse);
			
		}
		
	}
	
	$user = getUserDatas($connexion,$_SESSION['userid']);
	$adresse = getUserAddress($connexion,$_SESSION['userid']);
	
	require('Views/editProfile.php');
	
?>
